package com.example.extenddemo.config;

import cn.hutool.extra.spring.SpringUtil;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.*;

@EnableAsync(proxyTargetClass = true)
@AutoConfiguration
@Slf4j
public class AsyncAutoConfig implements AsyncConfigurer {

    /**
     * @Description: 自定义线程调度池
     * @return ScheduledExecutorService
     */
    @Bean
    public ScheduledExecutorService scheduledExecutorService(){
        ScheduledThreadPoolExecutor service = new ScheduledThreadPoolExecutor(10, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("scheduledExecutorService"+thread.getId());
                return thread;
            }
        }, new ThreadPoolExecutor.CallerRunsPolicy()) {
        };
        return service;
    }

    /**
     * @Description:  @Async注解获取线程池的方法
     * @return
     */
    @Override
    public Executor getAsyncExecutor() {
        log.info("getAsyncExecutor ==================================");
        return (Executor) SpringUtil.getApplicationContext().getBean("scheduledExecutorService");
    }

    @PreDestroy
    public void destroy() {
        log.info("destroy ==================================");
    }


}
